/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.Internals;

namespace NTasking
{

    public class SelectiveCallSyntaxNode
    {

        internal SelectiveCall Select { get; set; }

    }


    /// <summary>
    /// Implement Ada selective call statements
    /// </summary>
    public partial class SelectiveCall : SelectiveCallSyntaxNode
    {

        #region Internal Classes

        // Contains various classes and extension methods which allow to implement the fluent syntax
        // for writing a selective call

        public class BeforeThenAbort : SelectiveCallSyntaxNode
        {

            public Complete ThenAbort(Action abortablePart)
            {
                Select.AbortablePart = abortablePart;

                return new Complete { Select = Select };
            }

        }


        public class AfterCallContinuation : BeforeThenAbort
        {

            public AfterOrDelay OrDelay(int milliseconds)
            {
                Select.Timeout = new Timeout(milliseconds);
                Select.CurrentContinuable = Select.Timeout;

                return new AfterOrDelay { Select = Select };
            }


            public AfterOrDelay OrDelay(TimeSpan duration)
            {
                Select.Timeout = new Timeout(duration);
                Select.CurrentContinuable = Select.Timeout;

                return new AfterOrDelay { Select = Select };
            }


            public AfterOrDelay OrDelay(double seconds)
            {
                Select.Timeout = new Timeout(seconds);
                Select.CurrentContinuable = Select.Timeout;

                return new AfterOrDelay { Select = Select };
            }


            public AfterOrDelay OrDelay(DateTime until)
            {
                Select.Timeout = new Timeout(until);
                Select.CurrentContinuable = Select.Timeout;

                return new AfterOrDelay { Select = Select };
            }


            public Complete Else(Action elseStatements)
            {
                Select.Else = elseStatements;

                return new Complete { Select = Select };
            }

        }


        public class AfterActionCall : AfterCallContinuation
        {

            public AfterCallContinuation Then(Action continuation)
            {
                Select.CurrentContinuable.Continuation = continuation;

                return new AfterCallContinuation { Select = Select };
            }

        }


        public class AfterFuncCall<RetT> : AfterCallContinuation
        {

            public AfterCallContinuation Then(Action<RetT> continuation)
            {
                Select.GetContextualContinuable<RetT>().ContextualContinuation = continuation;

                return new AfterCallContinuation { Select = Select };
            }

        }


        public class AfterOrDelay : Complete
        {

            public Complete Then(Action continuation)
            {
                Select.CurrentContinuable.Continuation = continuation;

                return new Complete { Select = Select };
            }

        }


        public class AfterDelay : BeforeThenAbort
        {

            public BeforeThenAbort Then(Action continuation)
            {
                Select.CurrentContinuable.Continuation = continuation;

                return new BeforeThenAbort { Select = Select };
            }

        }


        public class Complete : SelectiveCallSyntaxNode { }

        #endregion


        private object _currentContextualContinuable;

        private MethodCall _call;


        /// <summary>
        /// Gets or sets the <see cref="IContinuable"/> last seen while building this instance.
        /// </summary>
        /// <value>The current continuable.</value>
        internal IContinuable CurrentContinuable { get; set; }


        /// <summary>
        /// Gets or sets the timeout alternative.
        /// </summary>
        /// <value>The timeout alternative.</value>
        internal Timeout Timeout { get; set; }


        /// <summary>
        /// Gets or sets the else alternative.
        /// </summary>
        /// <value>The else alternative.</value>
        internal Action Else { get; set; }


        /// <summary>
        /// Gets or sets the abortable part.
        /// </summary>
        /// <value>The abortable part.</value>
        internal Action AbortablePart { get; set; }


        /// <summary>
        /// Execute a new selective call defined by the specified statements.
        /// </summary>
        /// <param name="statements">The statements.</param>
        internal static new void Select(Func<SelectiveCall, Complete> statements)
        {
            if (statements == null)
                throw new ArgumentNullException("statements");

            // Check that this instance can be blocked since select is an Ada
            // 'potentially blocking operation'
            if (!ThreadWrapper.CurrentThread.CanBlock)
                throw Errors.PotentiallyBlockingOperationNotAllowed("select");

            var s = new SelectiveCall();

            statements(s);

            s.Execute();
        }


        /// <summary>
        /// Initializes a new instance of the <see cref="SelectiveCall"/> class.
        /// </summary>
        internal SelectiveCall()
        {
            base.Select = this;
        }


        /// <summary>
        /// Sets the <see cref="IContinuable{RetT}"/> last seen while building this instance.
        /// </summary>
        /// <typeparam name="RetT">The type of the result passed to the continuation.</typeparam>
        /// <param name="continuable">The continuable.</param>
        internal void SetContextualContinuable<RetT>(IContinuable<RetT> continuable)
        {
            _currentContextualContinuable = continuable;
        }


        /// <summary>
        /// Gets the <see cref="IContinuable{RetT}"/> last seen while building this instance.
        /// </summary>
        /// <typeparam name="RetT">The type of the result passed to the continuation.</typeparam>
        /// <returns>The continuable</returns>
        internal IContinuable<RetT> GetContextualContinuable<RetT>()
        {
            return _currentContextualContinuable as IContinuable<RetT>;
        }


        /// <summary>
        /// Executes this instance.
        /// </summary>
        private void Execute()
        {
            if (Else != null)
            {
                SynchronizedObject.ConditionalEntryCall(_call);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
                else
                    Else();
            }
            else if (AbortablePart != null)
            {
                if (!ThreadWrapper.CurrentThread.Abortable)
                    throw Errors.AsynchronousSelectNotAllowed();

                SynchronizedObject.AsynchronousSelect(_call, AbortablePart);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
            }
            else
            {
                Timeout.Freeze();

                SynchronizedObject.TimedEntryCall(_call, Timeout.Value);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
                else
                    Timeout.Continue();
            }
        }


        /// <summary>
        /// Set the call which must be selectively performed.
        /// </summary>
        /// <param name="selectiveCall">The call.</param>
        /// <returns></returns>
        internal AfterActionCall CreateActionCall(MethodCall selectiveCall)
        {
            _call = selectiveCall;

            CurrentContinuable = selectiveCall;

            return new AfterActionCall { Select = this };
        }


        /// <summary>
        /// Set the call which must be selectively performed.
        /// </summary>
        /// <param name="selectiveCall">The call.</param>
        /// <returns></returns>
        internal AfterFuncCall<RetT> CreateFuncCall<RetT>(MethodCall selectiveCall)
        {
            _call = selectiveCall;

            SetContextualContinuable((IContinuable<RetT>)selectiveCall);

            return new AfterFuncCall<RetT> { Select = this };
        }


        /// <summary>
        /// Add a selective delay alternative
        /// </summary>
        /// <param name="seconds">The delay in seconds.</param>
        /// <returns></returns>
        public AfterDelay Delay(double seconds)
        {
            return Delay(TimeSpan.FromSeconds(seconds));
        }


        /// <summary>
        /// Add a selective delay alternative
        /// </summary>
        /// <param name="milliseconds">The delay in milliseconds.</param>
        /// <returns></returns>
        public AfterDelay Delay(int milliseconds)
        {
            return Delay(TimeSpan.FromMilliseconds(milliseconds));
        }


        /// <summary>
        /// Add a selective delay alternative
        /// </summary>
        /// <param name="interval">The delay interval.</param>
        /// <returns></returns>
        public AfterDelay Delay(TimeSpan interval)
        {
            return Delay(DateTime.Now + interval);
        }


        /// <summary>
        /// Add a selective delay alternative
        /// </summary>
        /// <param name="deadline">The delay end.</param>
        /// <returns></returns>
        public AfterDelay Delay(DateTime deadline)
        {
            Internals.Delay.SelectiveDelayCall(this, deadline);

            return new AfterDelay { Select = this };
        }


        // TODO: Comment
        private SCallDelegateT GetCall<CallDelegateT, SCallDelegateT>(CallDelegateT selectiveCall)
            where CallDelegateT : class
            where SCallDelegateT : class
        {
            // Check that this instance can be blocked since select is an Ada
            // 'potentially blocking operation'
            if (!ThreadWrapper.CurrentThread.CanBlock)
                throw Errors.PotentiallyBlockingOperationNotAllowed("select");

            if (selectiveCall == null)
                throw Errors.SelectiveCallIsNull();

            // ReSharper disable PossibleNullReferenceException
            object target = (selectiveCall as MulticastDelegate).Target;
            // ReSharper restore PossibleNullReferenceException

            var callable1 = target as ISynchronouslyCallable<CallDelegateT>;
            var callable2 = target as ISelectivelyCallable<SCallDelegateT>;

            if (callable1 == null || callable2 == null)
                throw Errors.SelectiveCallNotSynchronized(selectiveCall);

            if (!((SynchronizedMethod)target).IsEntry)
                throw Errors.SelectiveCallNotAnEntry(selectiveCall);

            return callable2.SelectiveCall(this);
        }

    }

}
